package com.sxfq.loansupermarket.backsystem.modular.marketing.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.DateUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.listManagement;
import com.sxfq.loansupermarket.backsystem.modular.marketing.dao.ReservationsDao;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.SearchReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.TongJiInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;


/**
 * @author hzp
 * @Date
 */
@Controller
@RequestMapping("/reservation")
public class ReservationsRecordController extends BaseController {

    @Autowired
    IReservationsService reservationsService;

    @Autowired
    private ReservationsDao dao;

    private String PREFIX = "/marketing/reservations/";

    @Autowired
    private SqlMapper sqlMapper;


    /**
     * 跳转到市场预约  建档
     */
    @RequestMapping("/reservationsRecord")
    public String reservationsRecord(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/reservationsRecord.html";
    }

    /**
     * 跳转到市场预约  已到
     */
    @RequestMapping("/reservationsArrived")
    public String reservationsArrived(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/reservations_arrived.html";
    }

    /**
     * 跳转到市场预约  未到
     */
    @RequestMapping("/reservationsNoArrived")
    public String reservationsNoArrived(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/reservations_no_arrived.html";
    }

    /**
     * 跳转到市场预约  预约回访
     */
    @RequestMapping("/record")
    public String record(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/revisit_record.html";
    }

    /**
     * 跳转到市场回访统计页面
     */
    @RequestMapping("/statistics")
    public String statistics(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/revisit_return_visit_statistics.html";
    }

    /**
     * 跳转到预约客户管理添加页面
     */
    @RequestMapping(value = "/reservations_addTo")
    public String reservations_addTo(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "reservations_addTo.html";
    }

    /**
     * 点击姓名跳转客户管理详情页面
     */
    @RequestMapping(value = "/to_reservationsDetail/{id}")
    public String to_reservationsDetail(@PathVariable String id, Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ReservationsInfo reservationsInfo = this.reservationsService.selectOneById(id);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("reservationsInfo", reservationsInfo);
        return PREFIX + "reservationsDetail.html";
    }

    /**
     * 未到点击姓名跳转客户管理详情页面
     */
    @RequestMapping(value = "/to_reservationsNotDetail/{id}")
    public String to_reservationsNotDetail(@PathVariable String id, Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ReservationsInfo reservationsInfo = this.reservationsService.selectOneById(id);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("reservationsInfo", reservationsInfo);
        return PREFIX + "reservationsNotDetail.html";
    }

    /**
     * 市场部预约管理  建档    未到  列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object reservationsRecord(SearchReservationsInfo info, HttpServletRequest request) {
        Page<ReservationsInfo> page = new PageFactory<ReservationsInfo>().defaultPage();
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return REDIRECT + "/login";
        }
        try {
//            reservationsService.updateOneChannle();
            info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
            info.setLimitIndex(page.getSize());
            page.setCurrent(0);
            List<ReservationsInfo> list = reservationsService.selectPageListByStatusMap(page, info);
            if (list.size() == 0) {
                info.setStartIndex(0);
                list = reservationsService.selectPageListByStatusMap(page, info);
            }
            page.setRecords(list);
            page.setTotal(reservationsService.getQueryPagesCount(page, info));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 市场部预约管理 已到 列表
     */
    @RequestMapping("/listYD")
    @ResponseBody
    public Object listYD(SearchReservationsInfo info, HttpServletRequest request) {
        Page<ReservationsInfo> page = new PageFactory<ReservationsInfo>().defaultPage();
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return REDIRECT + "/login";
        }
        try {
//            reservationsService.updateOneChannle();
            info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
            info.setLimitIndex(page.getSize());
            page.setCurrent(0);
            List<ReservationsInfo> list = reservationsService.selectPageListByStatusMapYD(page, info);
            if (list.size() == 0) {
                info.setStartIndex(0);
                list = reservationsService.selectPageListByStatusMapYD(page, info);
            }
            page.setRecords(list);
            page.setTotal(reservationsService.getQueryPagesCount(page, info));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 统计查询
     */
    @RequestMapping(value = "/tongji", method = RequestMethod.GET)
    @ResponseBody
    public List<TongJiInfo> change(String param1, String param2, String param3, String param4, String param5, String param6, String param7, String param8, String param9, String param10, String param11, String param12) throws Exception {
        //1.获取当前日期，格式为yyyy-MM-dd hh:mm:ss
        String currentDate = DateUtil.getTime(new Date()).substring(0, 10);//取今天的年月日

        //获取昨天日期字符串 格式为yyyy-MM-dd hh:mm:ss
        String lastDate = DateUtil.getAfterDayDate("-1").substring(0, 10);//取昨日 的年月日

        //获取当月的字符串
        String currerntMonth = currentDate.substring(0, 7);//yyyy-mm

        //获取上月日期
        String lastMonth = DateUtil.getAfterDayMonth("-1").substring(0, 7);//取上月的年月

        String contitionInfo = "";
        if (StringUtils.isNotBlank(param1)) {
            contitionInfo += " and t.outpatient_name= '" + param1 + "' ";
        }
        if (StringUtils.isNotBlank(param2)) {
//            String sql = "select a.id from role a where a.name='" + param2 + "'";
//            UserDto dto = sqlMapper.selectOne(sql, UserDto.class);
//            contitionInfo += " and t1.roleid= '" + dto.getId() + "' ";
            contitionInfo += " and t.department= '" + param2 + "' ";
        }
        if (StringUtils.isNotBlank(param3)) {
            contitionInfo += " and t.archiving= '" + param3 + "' ";
        }
        if (StringUtils.isNotBlank(param4)) {
            if (!"请选择".equals(param4)) {
                contitionInfo += " and t.thr_channel= '" + param4 + "' ";
            }
        }
        if (StringUtils.isNotBlank(param5)) {
            if (!"请选择".equals(param5)) {
                contitionInfo += " and t.two_channel= '" + param5 + "' ";
            }
        }
        if (StringUtils.isNotBlank(param6)) {
            if (!"请选择".equals(param6)) {
                contitionInfo += " and t.one_channel= '" + param6 + "' ";
            }
        }
        if (StringUtils.isNotBlank(param7)) {
            contitionInfo += " and t.statuss= '" + param7 + "' ";
        }
        if (StringUtils.isNotBlank(param8)) {
            contitionInfo += " and t.access_disease= '" + param8 + "' ";
        }
        if (StringUtils.isNotBlank(param9)) {
            contitionInfo += " and t.appointment_pay_service= '" + param9 + "' ";
        }
        if (StringUtils.isNotBlank(param10)) {
            contitionInfo += " and t.status= '" + param10 + "' ";
        }
        if (StringUtils.isNotBlank(param11)) {
            contitionInfo += " and t.follower= '" + param11 + "' ";
        }
        if (StringUtils.isNotBlank(param12)) {
            contitionInfo += " and t.belonger= '" + param12 + "' ";
        }
        contitionInfo += "  group by t.id ,t.filing_time) t ";
        //查询今日   建档   0
        String sql = "select count(*) as countNum from (select * from reservations_info t where t.filing_time like '" + currentDate + "%' " + contitionInfo + "  " +
                //查询今日  已到 1
                "union all select count(*) as countNum from (select *  from reservations_info t where first_visit_date like '" + currentDate + "%'and t.status='到店' " + contitionInfo +
                //查询今日未到   2
                " union all select count(*) as countNum from (select *  from reservations_info t where appointment_time like '" + currentDate + "%'and t.status !='到店' and t.one_channel!='直接上门' and t.one_channel!='老带新' " + contitionInfo +
                //查询昨日  建档  3
                " union all select count(*) as countNum from (select *  from reservations_info t where t.filing_time like '" + lastDate + "%' " + contitionInfo +
                //查询昨日已到   4
                " union all select count(*) as countNum from (select *  from reservations_info t where first_visit_date like '" + lastDate + "%'and t.status='到店' " + contitionInfo +
                //查询昨日未到   5
                " union all select count(*) as countNum from (select *  from reservations_info t where appointment_time like '" + lastDate + "%'and t.status !='到店' and t.one_channel!='直接上门' and t.one_channel!='老带新' " + contitionInfo +

                //查询当月建档  6
                " union all select count(*) as countNum from (select *  from reservations_info t where t.filing_time like '" + currerntMonth + "%' " + contitionInfo +

                //查询当月已到   7
                " union all select count(*) as countNum from (select *  from reservations_info t where first_visit_date like '" + currerntMonth + "%'and t.status='到店' " + contitionInfo +

                //查询当月未到  8
                " union all select count(*) as countNum from (select *  from reservations_info t where appointment_time like '" + currerntMonth + "%'and t.status !='到店'  and t.one_channel!='直接上门' and t.one_channel!='老带新' " + contitionInfo +

                //查询上月  建档 9
                " union all select count(*) as countNum from (select *  from reservations_info t where t.filing_time like '" + lastMonth + "%' " + contitionInfo +

                //查询上月已到   10
                " union all select count(*) as countNum from (select *  from reservations_info t where first_visit_date like '" + lastMonth + "%'and t.status='到店' " + contitionInfo +

                //查询上月未到  11
                " union all select count(*) as countNum from (select *  from reservations_info t where appointment_time like '" + lastMonth + "%'and t.status !='到店'  and t.one_channel!='直接上门' and t.one_channel!='老带新' " + contitionInfo;

        List<TongJiInfo> tongJiInfoList = sqlMapper.selectList(sql, TongJiInfo.class);
        return tongJiInfoList;
    }


    /**
     * 选择建档人
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/to_archiving")
    public String to_archiving(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "archiving.html";
    }

    /**
     * 表格筛选
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/reservation_screenTable/{menuName}")
    public String reservation_screenTable(@PathVariable String menuName,Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String userName = ShiroKit.getUser().getAccount();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql ="select * from list_management where menuName='"+menuName+"' ";
        listManagement listManagement=sqlMapper.selectOne(sql,listManagement.class);

        String sqlsel ="select * from list_management_account " +
                " where account ='"+userName+"'  and menuName='"+menuName+"' ";
        listManagement listEcho=sqlMapper.selectOne(sqlsel,listManagement.class);
        if(listEcho!=null){
            model.addAttribute("listEcho", listEcho);
        }else{
            String sqlsel2 ="select count(*) as listx1  from list_management_account " +
                    " where account ='"+userName+"'  and menuName='"+menuName+"' ";
            listEcho=sqlMapper.selectOne(sqlsel2,listManagement.class);
            listEcho.setListx1("");
            model.addAttribute("listEcho", listEcho);
        }
        model.addAttribute("listManagement", listManagement);
        model.addAttribute("menuName", menuName);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "reservations_screenTable.html";
    }

    /**
     * 表格筛选
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/reservation_updateTable", method = RequestMethod.POST)
    @ResponseBody
    public int reservation_updateTable(String listx1,String menuName,String userName,Model model) {

        String sql ="select * from list_management_account where  account ='"+userName+"' " +
                " and menuName='"+menuName+"' ";
        listManagement listManagement=sqlMapper.selectOne(sql,listManagement.class);
        if(listManagement!=null){
            String sqlupdate ="update list_management_account set listx1='"+listx1+"' , update_time=now() " +
                    " where  account ='"+userName+"'  and menuName='"+menuName+"'" ;
            return sqlMapper.update(sqlupdate);
        }else{
            String sqladd ="insert into list_management_account " +
                    " (account,menuName,listx1,add_time,update_time)  " +
                    " values ('"+userName+"','"+menuName+"','"+listx1+"',now(),now())";
            return sqlMapper.insert(sqladd);
        }
    }

    /**
     * 表格加载
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/reservation_initialization", method = RequestMethod.POST)
    @ResponseBody
    public listManagement reservation_initialization(String menuName,Model model) {
        String userName = ShiroKit.getUser().getAccount();
        String sql ="select * from list_management_account where  account ='"+userName+"'  and menuName='"+menuName+"'" ;
        listManagement listManagement=sqlMapper.selectOne(sql,listManagement.class);
        return listManagement;
    }

    @RequestMapping(value = "/reservationsExport")
    public void reservationsExport(@RequestParam(required = false) String reach,
                                   @RequestParam(required = false) String appointmentPayService,
                                   @RequestParam(required = false) String archiving,
                                   @RequestParam(required = false) String follower,
                                   @RequestParam(required = false) String accessDisease,
                                   @RequestParam(required = false) String startFirstVisitDate,
                                   @RequestParam(required = false) String endFirstVisitDate,
                                   @RequestParam(required = false) String startFilingTime, @RequestParam(required = false) String startAppointmentTime,
                                   @RequestParam(required = false) String endFilingTime, @RequestParam(required = false) String endAppointmentTime,
                                   @RequestParam(required = false) String outpatientName, @RequestParam(required = false) String pageType,
                                   @RequestParam(required = false) String oneChannel, @RequestParam(required = false) String status,
                                   @RequestParam(required = false) String twoChannel, @RequestParam(required = false) String thrChannel,
                                   @RequestParam(required = false) String wechatNumber, @RequestParam(required = false) String statuss,
                                   @RequestParam(required = false) String department, HttpServletResponse response) {
        try {
            SearchReservationsInfo searchInfo = new SearchReservationsInfo();
            searchInfo.setReach(reach);
            searchInfo.setPageType(pageType);
            searchInfo.setStatuss(statuss);
            searchInfo.setStatus(status);
            searchInfo.setStartFirstVisitDate(startFirstVisitDate);
            searchInfo.setEndFirstVisitDate(endFirstVisitDate);
            searchInfo.setAppointmentPayService(appointmentPayService);
            searchInfo.setArchiving(archiving);
            searchInfo.setAccessDisease(accessDisease);
            searchInfo.setStartFilingTime(startFilingTime);
            searchInfo.setEndFilingTime(endFilingTime);
            searchInfo.setOutpatientName(outpatientName);
            searchInfo.setStartAppointmentTime(startAppointmentTime);
            searchInfo.setEndAppointmentTime(endAppointmentTime);
            searchInfo.setOneChannel(oneChannel);
            searchInfo.setTwoChannel(twoChannel);
            searchInfo.setThrChannel(thrChannel);
            searchInfo.setWechatNumber(wechatNumber);
            searchInfo.setDepartment(department);
            searchInfo.setFollower(follower);
            List<ReservationsInfo> list = reservationsService.reservationsExport(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
//            if("1".equals(pageType)){
            for (int i = 0; i < 26; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("性别");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("年龄");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("电话号码");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("疾病类型");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("咨询内容");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("媒体来源");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("详细来源");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("搜索关键词");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("备注");
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue("客服");
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue("到店时间");
            cell.setCellStyle(style);
            cell = row.createCell(12);
            cell.setCellValue("添加时间");
            cell.setCellStyle(style);
            cell = row.createCell(13);
            cell.setCellValue("接待医生");
            cell.setCellStyle(style);
            cell = row.createCell(14);
            cell.setCellValue("消费状态");
            cell.setCellStyle(style);
            cell = row.createCell(15);
            cell.setCellValue("消费项目");
            cell.setCellStyle(style);
            cell = row.createCell(16);
            cell.setCellValue("消费明细");
            cell.setCellStyle(style);
            cell = row.createCell(17);
            cell.setCellValue("回访时间");
            cell.setCellStyle(style);
            cell = row.createCell(18);
            cell.setCellValue("回访记录");
            cell.setCellStyle(style);
            cell = row.createCell(19);
            cell.setCellValue("医生点评");
            cell.setCellStyle(style);
            cell = row.createCell(20);
            cell.setCellValue("部门");
            cell.setCellStyle(style);
            cell = row.createCell(21);
            cell.setCellValue("到院状态");
            cell.setCellStyle(style);
            cell = row.createCell(22);

            cell.setCellValue("微信");
            cell.setCellStyle(style);
            cell = row.createCell(23);
            cell.setCellValue("跟进人");
            cell.setCellStyle(style);
            cell = row.createCell(24);
            cell.setCellValue("预约门诊");
            cell.setCellStyle(style);
            cell = row.createCell(25);
            cell.setCellValue("初诊时间");
            cell.setCellStyle(style);
            cell = row.createCell(26);
            cell.setCellValue("一级渠道");
            cell.setCellStyle(style);


            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                ReservationsInfo map = list.get(i);
                row = sheet.createRow(i + 1);

                String reservationsNum = map.getReservationsNum();
                String customerName = map.getCustomerName();
                String customerPhone = map.getCustomerPhone();
                String remarks = map.getRemarks();

                wechatNumber = map.getWechatNumber();
                status = map.getStatus();
                statuss = map.getStatuss();
                String appointmentTime = map.getAppointmentTime();
                String appointmentArrivalTime = map.getAppointmentArrivalTime();
                String huifang = map.getHuifang();
                String jiedaiContent = map.getJiedaiContent();
                archiving = map.getArchiving();
                String filingTime = map.getFilingTime();
                String keyWord = map.getKeyWord();
                String firstVisitDate = map.getFirstVisitDate();  //首次到店时间
                oneChannel = map.getOneChannel();
                twoChannel = map.getTwoChannel();
                thrChannel = map.getThrChannel();
                String sex = map.getSex();
                follower = map.getFollower();
                Double money = 0.00;
                if (map.getMoney() != null) {
                    money = map.getMoney();
                }
                String tcName = map.getTcName();
                int customerAge = 0;
                if (map.getCustomerAge() != null) {
                    customerAge = map.getCustomerAge();
                }
                String dealStatus = map.getDealStatus();
                appointmentPayService = map.getAppointmentPayService();
                String accessDiseases = map.getAccessDisease();
                outpatientName = map.getOutpatientName();
                String expenditureProject = map.getExpenditureProject();
                department = map.getDepartment();
                String id = map.getId();
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 26; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(customerName);
                row.getCell(1).setCellValue(sex);
                row.getCell(2).setCellValue(customerAge);
                row.getCell(3).setCellValue(customerPhone);
                row.getCell(4).setCellValue(appointmentPayService);
                row.getCell(5).setCellValue(accessDiseases);
                row.getCell(6).setCellValue(twoChannel);
                row.getCell(7).setCellValue(thrChannel);
                row.getCell(8).setCellValue(keyWord);
                row.getCell(9).setCellValue(remarks);
                row.getCell(10).setCellValue(archiving);
                row.getCell(11).setCellValue(firstVisitDate);
                row.getCell(12).setCellValue(filingTime);
                row.getCell(13).setCellValue(tcName);
                row.getCell(14).setCellValue(dealStatus);
                row.getCell(15).setCellValue(expenditureProject);
                row.getCell(16).setCellValue(money);
                row.getCell(17).setCellValue(appointmentTime);
                row.getCell(18).setCellValue(huifang);
                row.getCell(19).setCellValue(jiedaiContent);
                row.getCell(20).setCellValue(department);
                row.getCell(21).setCellValue(status);


                row.getCell(22).setCellValue(wechatNumber);
                row.getCell(23).setCellValue(follower);
                row.getCell(24).setCellValue(outpatientName);

                row.getCell(25).setCellValue(firstVisitDate);
                row.getCell(26).setCellValue(oneChannel);
            }
//            }
//            else{
//                for (int i = 0; i < 19; i++) {
//                    sheet.setColumnWidth(i, 24 * 256);
//                }
//                // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
//                HSSFRow row = sheet.createRow(0);
//                // 第四步，创建单元格，并设置值表头 设置表头居中
//                HSSFCellStyle style = wb.createCellStyle();
//                style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
//                HSSFCell cell = row.createCell(0);
//                cell.setCellValue("姓名");
//                cell.setCellStyle(style);
//                cell = row.createCell(1);
//                cell.setCellValue("性别");
//                cell.setCellStyle(style);
//                cell = row.createCell(2);
//                cell.setCellValue("预约号");
//                cell.setCellStyle(style);
//                cell = row.createCell(3);
//                cell.setCellValue("初诊TC");
//                cell.setCellStyle(style);
//                cell = row.createCell(4);
//                cell.setCellValue("预约时间");
//                cell.setCellStyle(style);
//                cell = row.createCell(5);
//                cell.setCellValue("访问病种");
//                cell.setCellStyle(style);
//                cell = row.createCell(6);
//                cell.setCellValue("预约病种");
//                cell.setCellStyle(style);
//                cell = row.createCell(7);
//                cell.setCellValue("一级渠道");
//                cell.setCellStyle(style);
//                cell = row.createCell(8);
//                cell.setCellValue("二级渠道");
//                cell.setCellStyle(style);
//                cell = row.createCell(9);
//                cell.setCellValue("三级渠道");
//                cell.setCellStyle(style);
//                cell = row.createCell(10);
//                cell.setCellValue("电话");
//                cell.setCellStyle(style);
//                cell = row.createCell(11);
//                cell.setCellValue("微信");
//                cell.setCellStyle(style);
//                cell = row.createCell(12);
//                cell.setCellValue("回访状态");
//                cell.setCellStyle(style);
//                cell = row.createCell(13);
//                cell.setCellValue("跟进人");
//                cell.setCellStyle(style);
//                cell = row.createCell(14);
//                cell.setCellValue("建档人");
//                cell.setCellStyle(style);
//                cell = row.createCell(15);
//                cell.setCellValue("成交状态");
//                cell.setCellStyle(style);
//                cell = row.createCell(16);
//                cell.setCellValue("成交金额");
//                cell.setCellStyle(style);
//                cell = row.createCell(17);
//                cell.setCellValue("建档时间");
//                cell.setCellStyle(style);
//                cell = row.createCell(18);
//                cell.setCellValue("年龄");
//                cell.setCellStyle(style);
//                cell = row.createCell(19);
//                cell.setCellValue("消费项目");
//                cell.setCellStyle(style);
//                cell = row.createCell(20);
//                cell.setCellValue("预约门诊");
//                cell.setCellStyle(style);
//                cell = row.createCell(21);
//                cell.setCellValue("到店状态");
//                cell.setCellStyle(style);
//                cell = row.createCell(22);
//                cell.setCellValue("初诊时间");
//                cell.setCellStyle(style);
//                // 填充数据
//                for (int i = 0; i < list.size(); i++) {
//                    ReservationsInfo map = list.get(i);
//                    row = sheet.createRow(i + 1);
//
//                    String reservationsNum = map.getReservationsNum();
//                    String customerName = map.getCustomerName();
//                    String customerPhone = map.getCustomerPhone();
//                    wechatNumber = map.getWechatNumber();
//                    status = map.getStatus();
//                    statuss = map.getStatuss();
//                    String appointmentTime=map.getAppointmentTime();
//                    archiving = map.getArchiving();
//                    String filingTime= map.getFilingTime();
//                    String firstVisitDate = map.getFirstVisitDate();  //首次到店时间
//                    oneChannel = map.getOneChannel();
//                    twoChannel = map.getTwoChannel();
//                    thrChannel = map.getThrChannel();
//                    String sex = map.getSex();
//                    int customerAge = 0;
//                    if (map.getCustomerAge() != null) {
//                        customerAge = map.getCustomerAge();
//                    }
//                    String dealStatus = map.getDealStatus();
//                    appointmentPayService = map.getAppointmentPayService();
//                    String accessDiseases = map.getAccessDisease();
//                    outpatientName = map.getOutpatientName();
//
//                    String id = map.getId();
//                    // 第四步，创建单元格，并设置值
//                    for (int j = 0; j <= 18; j++) {
//                        row.createCell(j).setCellStyle(style);
//                    }
//                    row.getCell(0).setCellValue(reservationsNum);
//                    row.getCell(1).setCellValue(customerName);
//                    row.getCell(2).setCellValue(customerPhone);
//                    row.getCell(3).setCellValue(wechatNumber);
//                    row.getCell(4).setCellValue(status);
//                    row.getCell(5).setCellValue(statuss);
//                    row.getCell(6).setCellValue(appointmentTime);
//                    row.getCell(7).setCellValue(archiving);
//                    row.getCell(8).setCellValue(filingTime);
//                    row.getCell(9).setCellValue(firstVisitDate);
//                    row.getCell(10).setCellValue(oneChannel);
//                    row.getCell(11).setCellValue(twoChannel);
//                    row.getCell(12).setCellValue(thrChannel);
//                    row.getCell(13).setCellValue(sex);
//                    row.getCell(14).setCellValue(customerAge);
//                    row.getCell(15).setCellValue(dealStatus);
//                    row.getCell(16).setCellValue(appointmentPayService);
//                    row.getCell(17).setCellValue(accessDiseases);
//                    row.getCell(18).setCellValue(outpatientName);
//                }
//            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //已到导出
    @RequestMapping(value = "/reservationsExportYD")
    public void reservationsExportYD(@RequestParam(required = false) String reach,
                                     @RequestParam(required = false) String appointmentPayService,
                                     @RequestParam(required = false) String archiving,
                                     @RequestParam(required = false) String follower,
                                     @RequestParam(required = false) String accessDisease,
                                     @RequestParam(required = false) String startFirstVisitDate,
                                     @RequestParam(required = false) String endFirstVisitDate,
                                     @RequestParam(required = false) String startFilingTime, @RequestParam(required = false) String startAppointmentTime,
                                     @RequestParam(required = false) String endFilingTime, @RequestParam(required = false) String endAppointmentTime,
                                     @RequestParam(required = false) String arrivalStore, @RequestParam(required = false) String pageType,
                                     @RequestParam(required = false) String oneChannel, @RequestParam(required = false) String status,
                                     @RequestParam(required = false) String twoChannel, @RequestParam(required = false) String thrChannel,
                                     @RequestParam(required = false) String wechatNumber, @RequestParam(required = false) String statuss,
                                     @RequestParam(required = false) String department, HttpServletResponse response) {
        try {
            SearchReservationsInfo searchInfo = new SearchReservationsInfo();
            searchInfo.setReach(reach);
            searchInfo.setPageType(pageType);
            searchInfo.setStatuss(statuss);
            searchInfo.setStatus(status);
            searchInfo.setStartFirstVisitDate(startFirstVisitDate);
            searchInfo.setEndFirstVisitDate(endFirstVisitDate);
            searchInfo.setAppointmentPayService(appointmentPayService);
            searchInfo.setArchiving(archiving);
            searchInfo.setAccessDisease(accessDisease);
            searchInfo.setStartFilingTime(startFilingTime);
            searchInfo.setEndFilingTime(endFilingTime);
            searchInfo.setArrivalStore(arrivalStore);
            searchInfo.setStartAppointmentTime(startAppointmentTime);
            searchInfo.setEndAppointmentTime(endAppointmentTime);
            searchInfo.setOneChannel(oneChannel);
            searchInfo.setTwoChannel(twoChannel);
            searchInfo.setThrChannel(thrChannel);
            searchInfo.setWechatNumber(wechatNumber);
            searchInfo.setDepartment(department);
            searchInfo.setFollower(follower);
            List<ReservationsInfo> list = reservationsService.reservationsExportYD(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
//            if("1".equals(pageType)){
            for (int i = 0; i < 26; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("性别");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("年龄");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("电话号码");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("疾病类型");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("咨询内容");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("媒体来源");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("详细来源");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("搜索关键词");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("备注");
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue("客服");
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue("到店时间");
            cell.setCellStyle(style);
            cell = row.createCell(12);
            cell.setCellValue("添加时间");
            cell.setCellStyle(style);
            cell = row.createCell(13);
            cell.setCellValue("接待医生");
            cell.setCellStyle(style);
            cell = row.createCell(14);
            cell.setCellValue("消费状态");
            cell.setCellStyle(style);
            cell = row.createCell(15);
            cell.setCellValue("消费项目");
            cell.setCellStyle(style);
            cell = row.createCell(16);
            cell.setCellValue("消费明细");
            cell.setCellStyle(style);
            cell = row.createCell(17);
            cell.setCellValue("回访时间");
            cell.setCellStyle(style);
            cell = row.createCell(18);
            cell.setCellValue("回访记录");
            cell.setCellStyle(style);
            cell = row.createCell(19);
            cell.setCellValue("医生点评");
            cell.setCellStyle(style);
            cell = row.createCell(20);
            cell.setCellValue("部门");
            cell.setCellStyle(style);
            cell = row.createCell(21);
            cell.setCellValue("到院状态");
            cell.setCellStyle(style);
            cell = row.createCell(22);

            cell.setCellValue("微信");
            cell.setCellStyle(style);
            cell = row.createCell(23);
            cell.setCellValue("跟进人");
            cell.setCellStyle(style);
            cell = row.createCell(24);
            cell.setCellValue("预约门诊");
            cell.setCellStyle(style);
            cell = row.createCell(25);
            cell.setCellValue("初诊时间");
            cell.setCellStyle(style);
            cell = row.createCell(26);
            cell.setCellValue("一级渠道");
            cell.setCellStyle(style);


            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                ReservationsInfo map = list.get(i);
                row = sheet.createRow(i + 1);

                String reservationsNum = map.getReservationsNum();
                String customerName = map.getCustomerName();
                String customerPhone = map.getCustomerPhone();
                String remarks = map.getRemarks();

                wechatNumber = map.getWechatNumber();
                status = map.getStatus();
                statuss = map.getStatuss();
                String appointmentTime = map.getAppointmentTime();
                String appointmentArrivalTime = map.getAppointmentArrivalTime();
                String huifang = map.getHuifang();
                String jiedaiContent = map.getJiedaiContent();
                archiving = map.getArchiving();
                String filingTime = map.getFilingTime();
                String keyWord = map.getKeyWord();
                String firstVisitDate = map.getFirstVisitDate();  //首次到店时间
                oneChannel = map.getOneChannel();
                twoChannel = map.getTwoChannel();
                thrChannel = map.getThrChannel();
                String sex = map.getSex();
                follower = map.getFollower();
                Double money = 0.00;
                if (map.getMoney() != null) {
                    money = map.getMoney();
                }
                String tcName = map.getTcName();
                int customerAge = 0;
                if (map.getCustomerAge() != null) {
                    customerAge = map.getCustomerAge();
                }
                String dealStatus = map.getDealStatus();
                appointmentPayService = map.getAppointmentPayService();
                String accessDiseases = map.getAccessDisease();
                arrivalStore = map.getArrivalStore();
                String expenditureProject = map.getExpenditureProject();
                department = map.getDepartment();
                String id = map.getId();
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 26; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(customerName);
                row.getCell(1).setCellValue(sex);
                row.getCell(2).setCellValue(customerAge);
                row.getCell(3).setCellValue(customerPhone);
                row.getCell(4).setCellValue(appointmentPayService);
                row.getCell(5).setCellValue(accessDiseases);
                row.getCell(6).setCellValue(twoChannel);
                row.getCell(7).setCellValue(thrChannel);
                row.getCell(8).setCellValue(keyWord);
                row.getCell(9).setCellValue(remarks);
                row.getCell(10).setCellValue(archiving);
                row.getCell(11).setCellValue(firstVisitDate);
                row.getCell(12).setCellValue(filingTime);
                row.getCell(13).setCellValue(tcName);
                row.getCell(14).setCellValue(dealStatus);
                row.getCell(15).setCellValue(expenditureProject);
                row.getCell(16).setCellValue(money);
                row.getCell(17).setCellValue(appointmentTime);
                row.getCell(18).setCellValue(huifang);
                row.getCell(19).setCellValue(jiedaiContent);
                row.getCell(20).setCellValue(department);
                row.getCell(21).setCellValue(status);


                row.getCell(22).setCellValue(wechatNumber);
                row.getCell(23).setCellValue(follower);
                row.getCell(24).setCellValue(arrivalStore);

                row.getCell(25).setCellValue(firstVisitDate);
                row.getCell(26).setCellValue(oneChannel);
            }

            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

